package com.example.hotitemanalysis;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;

public class KafkaProducerUtil {
    public static void main(String[] args) {
        writeToKafka("topic-hotitems");
    }

    public static void writeToKafka(String topic) {
        Properties properties = new Properties();
        properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "139.198.108.148:9092");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<String, String>(properties);

        //缓冲区读取文本
        try {
            URL resource = KafkaProducerUtil.class.getResource("/UserBehavior.csv");
            BufferedReader bufferedReader = new BufferedReader(new FileReader(resource.getPath()));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                ProducerRecord<String, String> producerRecord = new ProducerRecord<>(topic, line);
                //发送数据
                kafkaProducer.send(producerRecord);
            }
            kafkaProducer.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
